package com.iflytek.uoamp.agent.monitor.lib.statics;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Statics {
	
	private static int interval = 60;
	private int time = 0;
	private volatile Map<String,Long> sumStatics = new HashMap<String,Long>();
	private Lock lock = new ReentrantLock();
	public Lock alllock = new ReentrantLock();
	
	public static int getInterval() {
		return interval;
	}

	public static void setInterval(int interval) {
		Statics.interval = interval;
	}

	public void addRunTime(){
		time++;
	}
	
	public void cleanRunTime(){
		time=0;
	}

	public boolean isSend(){
		return time>=interval;
	}
	
	public void addTime(String key,long time){
		alllock.lock();
		lock.lock();
		try{
			Long number = sumStatics.get(key);
			if(number==null){
				number = Long.valueOf(0);
			}
			number = time+number;
			sumStatics.put(key, number);
		}finally{
			lock.unlock();
			alllock.unlock();
		}
	}
	
	public void add(String key){
		alllock.lock();
		lock.lock();
		try{
			Long number = sumStatics.get(key);
			if(number==null){
				number = Long.valueOf(0);
			}
			number++;
			sumStatics.put(key, number);
		}finally{
			lock.unlock();
			alllock.unlock();
		}
	}
	
	public double arv(String key,int times){
		alllock.lock();
		lock.lock();
		double result;
		try{
			Long number = sumStatics.get(key);
			if(number==null){
				number = Long.valueOf(0);
			}
			result = number/(double)times;
		}finally{
			lock.unlock();
			alllock.unlock();
		}
		return result;
	}
	
	public long getTime4Send(String key){
		lock.lock();
		Long number;
		try{
			number = sumStatics.get(key);
			if(number==null){
				number = Long.valueOf(0);
			}
		}finally{
			lock.unlock();
		}
		
		return number;
	}
	
	public void clean(){
		lock.lock();
		try{
		sumStatics.clear();
		}finally{
			lock.unlock();
		}
	}
	
	public Map<String,Long> getAllStatics(){
		alllock.lock();
		lock.lock();
		try{
			return new HashMap<String, Long>(sumStatics);
		}finally{
			lock.unlock();
			alllock.unlock();
		}
	}
	
}
